const { useState, useEffect } = React;
const { Modal, Button, Form, Input, Radio, Switch, Checkbox, message, Select, Col, Row } = antd;

const { Option } = Select;





const OptForm = (props) => {
  const { vars = [], opts = {}, prompt, visible, onCancel, onSubmit, width } = props;
  const [form] = Form.useForm();
  const [options, setOptions] = useState({});
  const [prompt_, setPrompt] = useState({});
  const [newOptions, setNewOptions] = useState({});
  const [loading, setLoading] = useState(false);

  // 初始化表单值和选项
  useEffect(() => {
    prn(vars, opts, prompt)

    form.setFieldsValue(prompt?.formValues || {});
    setOptions(opts || {});

    setPrompt(prompt?.content || {})
  }, [prompt, opts]);

  // 处理选项修改
  const handleOptionChange = (fieldName, index, value) => {
    const newItems = [...options[fieldName]];
    newItems[index] = value.trim();
    setOptions(prev => ({ ...prev, [fieldName]: newItems }));
  };

  // 处理新选项添加
  const handleAddOption = (fieldName) => {
    const value = newOptions[fieldName]?.trim();
    if (!value) return;

    setOptions(prev => ({
      ...prev,
      [fieldName]: [...(prev[fieldName] || []), value]
    }));
    setNewOptions(prev => ({ ...prev, [fieldName]: '' }));
  };

  // 渲染字段组件
  const renderField = (field) => {
    const { name, type } = field;
    const fieldOptions = options[name] || [];
    const inputStyle = { width: 160, marginRight: 8 };

    const renderOptionsEditor = () => (
      <Space direction="vertical" style={{ width: '100%' }}>
        {fieldOptions.map((opt, index) => (
          <Input
            key={index}
            value={opt}
            style={inputStyle}
            onChange={(e) => handleOptionChange(name, index, e.target.value)}
            placeholder="编辑选项"
          />
        ))}
        <Space>
          <Input
            style={inputStyle}
            value={newOptions[name] || ''}
            onChange={(e) => setNewOptions(prev => ({
              ...prev,
              [name]: e.target.value
            }))}
            placeholder="输入新选项"
          />
          <Button onClick={() => handleAddOption(name)}>添加</Button>
        </Space>
      </Space>
    );

    switch (type) {
      case 'input':
        return (
          <Form.Item key={name} name={name} label={name}>
            <Input />
          </Form.Item>
        );

      case 'switch':
        return (
          <Form.Item
            key={name}
            name={name}
            label={name}
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        );

      case 'radio':
        return (
          <Form.Item key={name} name={name} label={name}>
            <Radio.Group>
              <Space direction="vertical">
                {fieldOptions.map((opt, index) => (
                  <Radio key={index} value={opt}>
                    {opt}
                  </Radio>
                ))}
                {renderOptionsEditor()}
              </Space>
            </Radio.Group>
          </Form.Item>
        );

      case 'checkbox':
        return (
          <Form.Item key={name} name={name} label={name}>
            <Checkbox.Group>
              <Space direction="vertical">
                {fieldOptions.map((opt, index) => (
                  <Checkbox key={index} value={opt}>
                    {opt}
                  </Checkbox>
                ))}
                {renderOptionsEditor()}
              </Space>
            </Checkbox.Group>
          </Form.Item>
        );

      default:
        return null;
    }
  };

  const handleSubmit = () => {
    form.validateFields()
      .then(values => onSubmit({
        formValues: values,
        options: options
      }))
      .catch(console.error);
  };

  const format_prompt = async () => {
      let tpl = "Hello, {{ name }}!"
      let data = { name: "John Doe" }

      let formValues = await form.validateFields()

      tpl = prompt.content
      data = formValues
      const ret = $.template(tpl, data)

      prn('ret', ret, data)
      
      return ret
  }

  const doTest = async () => {
    console.log('Test click')

    prn(prompt)
    let formValues = await form.validateFields()

      let tpl = "Hello, {{ name }}!"
      let data = { name: "John Doe" }

      tpl = prompt.content
      data = formValues
      const ret = $.template(tpl, data)

      $.copyToClipboard(ret)
      // prn('ret', ret, data)

      if (window.editor){
        editor.setValue(ret)
      }
    
    // prn(options)
  }

  const doLLM = async () => {
    let tpl = await format_prompt()

    setLoading(true);
    let ret = await $.callQianfanAPI(tpl)
    setLoading(false);

    ret = ret.replace('```json', '')
    ret = ret.replace('```', '')
    const jsonString = ret 
    const parsedData = JSON.parse(jsonString);
    
    parsedData.forEach((book) => {
        console.log(`标题: ${book.title}`);
        console.log(`描述: ${book.description}`);
        console.log(`体裁: ${book.genre}`);
        console.log('-------------------');

        db.topic_ideas.add(book);
    });

    let editor = window['editor_opt_edit']
    if (editor){
      editor.setValue(ret)
    }
    
  }

  const updateDoc = ()=>{

  }

  return (
    <Modal
      title="动态表单"
      width={width?width:1600}
      visible={visible}
      onCancel={onCancel}
      footer={[
        <Button key="llm" onClick={doLLM} loading={loading}>LLM</Button>,
        <Button key="test" onClick={doTest}>Test</Button>,
        <Button key="cancel" onClick={onCancel}>取消</Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>提交</Button>
      ]}
    >



    <Row>
      <Col span={12}>
          <h2> name: {prompt? prompt?.name : ''}</h2>
          {prompt?prompt?.content: ''}

        <Form form={form} layout="vertical" initialValues={prompt?.formValues}>
          {vars.map(field => renderField(field))}
        </Form>  
      </Col>

    </Row>

    </Modal>
  );
};

